package service

import (
	"time"
	
	"gitee.com/liumou_site/disk-monitoring/backend/internal/model"
	"github.com/shirou/gopsutil/v3/process"
)

// ProcessService 进程服务接口
type ProcessService interface {
	// GetProcessIOStats 获取进程IO统计信息
	GetProcessIOStats() ([]*model.ProcessIOStat, error)
	
	// GetTopProcessIOStats 获取IO使用率最高的进程列表
	GetTopProcessIOStats(limit int) ([]*model.ProcessIOStat, error)
	
	// GetRealTimeProcessIOData 获取实时进程IO数据（仅包含性能相关数据）
	GetRealTimeProcessIOData() (*model.RealTimeProcessIOData, error)
}

// processService 进程服务实现
type processService struct {
	// 可以包含依赖的其他服务或数据访问对象
}

// NewProcessService 创建进程服务实例
func NewProcessService() ProcessService {
	return &processService{}
}

// GetProcessIOStats 获取进程IO统计信息
func (s *processService) GetProcessIOStats() ([]*model.ProcessIOStat, error) {
	processes, err := process.Processes()
	if err != nil {
		return nil, err
	}
	
	var processIOStats []*model.ProcessIOStat
	for _, p := range processes {
		ioCounters, err := p.IOCounters()
		if err != nil {
			continue
		}
		
		name, err := p.Name()
		if err != nil {
			name = "unknown"
		}
		
		createTime, err := p.CreateTime()
		if err != nil {
			createTime = 0
		}
		
		processIOStat := &model.ProcessIOStat{
			PID:        p.Pid,
			Name:       name,
			ReadBytes:  ioCounters.ReadBytes,
			WriteBytes: ioCounters.WriteBytes,
			ReadCount:  ioCounters.ReadCount,
			WriteCount: ioCounters.WriteCount,
			ReadSpeed:  0, // 需要通过连续采样计算
			WriteSpeed: 0, // 需要通过连续采样计算
			CreateTime: createTime,
		}
		
		processIOStats = append(processIOStats, processIOStat)
	}
	
	return processIOStats, nil
}

// GetTopProcessIOStats 获取IO使用率最高的进程列表
func (s *processService) GetTopProcessIOStats(limit int) ([]*model.ProcessIOStat, error) {
	processIOStats, err := s.GetProcessIOStats()
	if err != nil {
		return nil, err
	}
	
	// 按照读写总字节数排序
	// 这里简化处理，实际应用中可能需要更复杂的排序逻辑
	if len(processIOStats) > limit {
		processIOStats = processIOStats[:limit]
	}
	
	return processIOStats, nil
}

// GetRealTimeProcessIOData 获取实时进程IO数据（仅包含性能相关数据）
func (s *processService) GetRealTimeProcessIOData() (*model.RealTimeProcessIOData, error) {
	processes, err := process.Processes()
	if err != nil {
		return nil, err
	}
	
	var processIOStats []model.ProcessIOStat
	for _, p := range processes {
		ioCounters, err := p.IOCounters()
		if err != nil {
			continue
		}
		
		name, err := p.Name()
		if err != nil {
			name = "unknown"
		}
		
		processIOStat := model.ProcessIOStat{
			PID:        p.Pid,
			Name:       name,
			ReadBytes:  ioCounters.ReadBytes,
			WriteBytes: ioCounters.WriteBytes,
			ReadCount:  ioCounters.ReadCount,
			WriteCount: ioCounters.WriteCount,
			ReadSpeed:  0, // 需要通过连续采样计算
			WriteSpeed: 0, // 需要通过连续采样计算
		}
		
		processIOStats = append(processIOStats, processIOStat)
	}
	
	realTimeData := &model.RealTimeProcessIOData{
		Timestamp:      time.Now().Unix(),
		ProcessIOStats: processIOStats,
	}
	
	return realTimeData, nil
}